﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MenusHunter.WinRT.Common;
using MenusHunter.WinRT.Core.Services.Account;
using MenusHunter.WinRT.Core.ViewModels;
using MenusHunter.WinRT.UserControls;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ApplicationSettings;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace MenusHunter.WinRT.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class Home : MenusHunter.WinRT.Common.LayoutAwarePage
    {
        private HomePageViewModel _viewModel;
        private bool _foodPanelIsShowing = false;
        Rect _windowBounds;
        double _settingsWidth = 346;
        Popup _settingsPopup;

        public Home()
        {
            this.InitializeComponent();
            Window.Current.SizeChanged+=Current_SizeChanged;
            _viewModel = (HomePageViewModel) DataContext;
            _windowBounds = Window.Current.Bounds;
            SettingsPane.GetForCurrentView().CommandsRequested += HomePage_CommandsRequested;
        }

        private void Current_SizeChanged(object sender, WindowSizeChangedEventArgs e)
        {
            _windowBounds = Window.Current.Bounds;
        }

        private void HomePage_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand cmd = new SettingsCommand("Account", "Accounts", (x) =>
            {
                _settingsPopup = new Popup();
                _settingsPopup.Closed += OnPopupClosed;
                Window.Current.Activated += OnWindowActivated;
                _settingsPopup.IsLightDismissEnabled = true;
                _settingsPopup.Width = _settingsWidth;
                _settingsPopup.Height = _windowBounds.Height;

                var mypane = new AccountSettings {Width = _settingsWidth, Height = _windowBounds.Height};

                _settingsPopup.Child = mypane;
                _settingsPopup.SetValue(Canvas.LeftProperty, _windowBounds.Width - _settingsWidth);
                _settingsPopup.SetValue(Canvas.TopProperty, 0);
                _settingsPopup.IsOpen = true;
            });

            args.Request.ApplicationCommands.Add(cmd);
        }

        private void OnWindowActivated(object sender, WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == CoreWindowActivationState.Deactivated)
            {
                _settingsPopup.IsOpen = false;
            }
        }

        private void OnPopupClosed(object sender, object e)
        {

            Window.Current.Activated -= OnWindowActivated;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if(_viewModel!=null)
            {
               await _viewModel.GetListRestaurantsAround(0, 9);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if(e.Parameter==null)
            {
                Frame.Navigate(typeof (Login),"You must login!");
            }
            base.OnNavigatedTo(e);
        }
        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private async void RestarantGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var grid = sender as GridView;
            if(grid!=null && grid.SelectedIndex > -1)
            {
                if(!_foodPanelIsShowing)
                {
                    FoodsListIn.Begin();
                    _foodPanelIsShowing = true;
                }
                if (_viewModel != null)
                {
                    await _viewModel.GetFoodsForRestaurant();
                }
            }
           
        }

   

        private void HideFoodsPanelButton_Click(object sender, RoutedEventArgs e)
        {
            FoodsListOut.Begin();
            _foodPanelIsShowing = false;
            RestarantGrid.SelectedIndex = -1;
        }


        private void ViewAsMapButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof (MapView));
        }
    }
}
